/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.pmc.dwa.security.model.TUserDetails;

/**
 * @description SpringSecurity工具类
 * @author aokunsang
 * @date 2013-1-7
 */
public class SpringSecurityUtils {

	/**
	 * 获取当前用户的业务分区、用户名、用户ID、用户密码等信息
	 * @return
	 */
	public static TUserDetails getCurrentUser(){
		Authentication auth = getAuthentication();
		
		if(auth==null) return null;
		
		Object principal = auth.getPrincipal();
		if(principal instanceof TUserDetails){
			return (TUserDetails)principal;
		}
		return null;
	}
	/**
	 * 获取当前用户的业务分区、用户名、用户ID、用户密码等信息
	 * @param auth
	 * @return
	 */
	public static TUserDetails getCurrentUser(Authentication auth){
		
		if(auth==null) return null;
		
		Object principal = auth.getPrincipal();
		if(principal instanceof TUserDetails){
			return (TUserDetails)principal;
		}
		return null;
	}
	
	/**
	 * 取得Authentication, 如当前SecurityContext为空时返回null.
	 */
	public static Authentication getAuthentication() {
		SecurityContext context = SecurityContextHolder.getContext();
		if (context == null) {
			return null;
		}
		return context.getAuthentication();
	}
}
